package ynu.edu.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * 简单认证过滤器
 * 基础权限验证实现
 * 注意：不使用@Component，通过FilterConfig显式注册
 */
public class SimpleAuthFilter implements GlobalFilter, Ordered {

    public SimpleAuthFilter() {
        System.out.println("🔧 SimpleAuthFilter 构造函数执行 - 过滤器正在初始化");
    }

    @PostConstruct
    public void init() {
        System.out.println("🚀 SimpleAuthFilter 初始化完成 - 过滤器已加载，优先级: " + getOrder());
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String method = request.getMethod().name();
        
        System.out.println("==========================================");
        System.out.println("🔍 SimpleAuthFilter 执行中");
        System.out.println("📍 请求: " + method + " " + path);
        System.out.println("🌐 完整URI: " + request.getURI());
        
        // 🔧 重要修复：OPTIONS预检请求直接放行，不需要认证
        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            System.out.println("⚡ OPTIONS预检请求，直接放行（CORS需要）");
            System.out.println("==========================================");
            return chain.filter(exchange);
        }
        
        // 检查白名单路径
        if (isWhiteListPath(path)) {
            System.out.println("⚪ 白名单路径，跳过认证: " + path);
            System.out.println("==========================================");
            return chain.filter(exchange);
        }
        
        // 需要认证的路径
        System.out.println("🔐 需要认证的路径: " + path);
        
        String authHeader = request.getHeaders().getFirst("Authorization");
        System.out.println("🎫 Authorization头: " + (authHeader != null ? authHeader : "null"));
        
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            System.out.println("🚫 认证失败 - 缺少或格式不正确的Authorization头 (应为 'Bearer <token>')");
            System.out.println("==========================================");
            return buildUnauthorizedResponse(exchange.getResponse(), "Missing or invalid Authorization header. Use 'Bearer <token>'.");
        }
        
        String token = authHeader.substring(7); // "Bearer ".length() is 7
        
        if (!isValidToken(token)) {
            System.out.println("🚫 认证失败 - 无效Token: " + token);
            System.out.println("==========================================");
            return buildUnauthorizedResponse(exchange.getResponse(), "Invalid token provided");
        }
        
        System.out.println("✅ 认证通过 - Token: " + token);
        
        // 在请求头中添加用户信息
        ServerHttpRequest newRequest = request.mutate()
                .header("X-User-Id", "123")
                .header("X-User-Name", "TestUser")
                .header("X-Auth-Status", "authenticated")
                .build();
        
        System.out.println("🔄 添加用户信息到请求头，继续执行");
        System.out.println("==========================================");
        
        return chain.filter(exchange.mutate().request(newRequest).build());
    }

    /**
     * 检查是否是白名单路径
     */
    private boolean isWhiteListPath(String path) {
        // 明确的白名单路径
        String[] whiteList = {
            "/actuator",      // 监控端点
            "/test/ping",     // ping接口
            "/health",        // 健康检查
            "/monitor"        // 监控接口
        };
        
        for (String whitePath : whiteList) {
            if (path.startsWith(whitePath)) {
                System.out.println("🔍 匹配白名单: " + whitePath + " -> " + path);
                return true;
            }
        }
        
        // 特别注意：/test/auth-required 不在白名单中，需要认证
        System.out.println("🔍 不在白名单中，需要认证: " + path);
        return false;
    }

    /**
     * 简单的Token验证
     */
    private boolean isValidToken(String token) {
        if (!StringUtils.hasText(token)) return false;
        
        // 验证Token是否为预设的秘钥
        final String expectedToken = "secret-token-for-ynu-2025";
        boolean valid = expectedToken.equals(token);
        
        System.out.println("🔍 Token验证: '" + token + "' -> " + (valid ? "有效" : "无效") + " (期望: '" + expectedToken + "')");
        return valid;
    }

    /**
     * 构建401响应
     */
    private Mono<Void> buildUnauthorizedResponse(ServerHttpResponse response, String message) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        
        String body = String.format(
            "{\"error\":\"Unauthorized\",\"message\":\"%s\",\"status\":401,\"timestamp\":\"%s\"}",
            message,
            java.time.LocalDateTime.now().toString()
        );
        
        System.out.println("🚫 返回401响应: " + body);
        
        org.springframework.core.io.buffer.DataBuffer buffer = 
            response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        // 日志过滤器之后，认证过滤器执行
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
} 